<template>
  <div id="app">

    <el-container>
      <el-header>
        <el-tabs tab-position="right" style="height: 200px;margin-top:20px;">
          <el-tab-pane @click="activeIdx = 0">
            <span title="点名册" @click="initRoster(); activeIdx = 0" slot="label">
              <i class="el-icon-thumb icon_tab"></i>
            </span>
          </el-tab-pane>
          <el-tab-pane @click="activeIdx = 1">
            <span title="学生人员设置" @click="activeIdx = 1" slot="label">
              <i class="el-icon-setting icon_tab"></i>
            </span>
          </el-tab-pane>
        </el-tabs>
      </el-header>

      <el-main v-if="activeIdx == 0" id="thumb-container">
        <div id="category">
          <el-divider content-position="center">
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                {{ category }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="cat.label" v-bind="idx" v-for="(cat, idx) in getDownCategory()">{{
                    cat.label
                }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-divider>
        </div>
        <div id="name-container">
          {{ currentName || "点兵点将" }}
        </div>
        <div id="start-container">
          <el-button title="快捷键：空格" @click="startHacking">{{ starting ? "停止" : "开始" }}</el-button>
        </div>
      </el-main>
      <el-main v-if="activeIdx == 1" style="height: 100%;padding: 0px;margin-top:-25px;">
        <div id="setting-container">
          <div id="category-container">
            <el-tree :data="categories" ref="tree" @node-click="chooseCategory" node-key="id" highlight-current
              default-expand-all :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <i title="点击添加班级" v-if="data.id == 0" @click.stop="addClass()" class="el-icon-plus"></i>
                  <i title="点击删除班级" v-if="data.id != 0" @click.stop="deleteClass(data)" class="el-icon-delete"></i>
                </span>
              </span>
            </el-tree>
          </div>
          <div id="roll-container">
            <el-form :inline="true" class="demo-form-inline">
              <el-button type="primary" @click="showAddNameView" icon="el-icon-plus" size="small">添加学生
              </el-button>
              <el-dialog title="添加学生" :visible.sync="addStudentViewShow">
                <el-input type="textarea" :rows="10" placeholder="输入学生姓名，一行一个" v-model="names">
                </el-input>
                <div slot="footer" class="dialog-footer">
                  <el-button size="small" @click="addStudentViewShow = false; names = ''">取 消</el-button>
                  <el-button size="small" type="primary" @click="addNames()">确 定</el-button>
                </div>
              </el-dialog>
              <el-input v-model="searchName" placeholder="输入姓名搜索" style="width: 360px;" size="small" clearable>
              </el-input>
            </el-form>
            <el-table :data="filter(rosters)" style="height:calc(100% - 20px);" ref="table"
              :max-height="tableMaxTable()">
              <el-table-column type="index" width="50" />
              <el-table-column prop="name" label="姓名" width="150" />
              <el-table-column prop="category" label="班级" width="100" />
              <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button @click="deleteRow(scope.row)" type="text" size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
console.log("app.vue");
import hotkeys from 'hotkeys-js';

export default {
  data() {

    return {
      categories: [],
      activeIdx: 0,
      names: "",
      addStudentViewShow: false,
      category: "默认班级",
      cs: [],
      currentName: undefined,
      starting: false,
      roster: [],
      rosters: [],
      timer: undefined,
      searchName: undefined,
      searchCategory: undefined
    };
  },
  methods: {
    tableMaxTable() {
      return document.body.clientHeight - 85;
    },
    filter(rosters) {
      if (!this.searchName &&
        !this.searchCategory) {
        return rosters;
      }
      var searchCategory = this.searchCategory;
      var searchName = this.searchName;

      var filterRosters = [];
      for (const idx in rosters) {
        var roster = rosters[idx]
        if (!searchCategory ||
          roster['category'] == searchCategory) {
          if (!searchName ||
            roster['name'].includes(searchName)) {
            filterRosters.push(roster);
          }
        }
      }
      return filterRosters;
    },
    getDownCategory() {
      if (this.categories.length == 0) {
        return [];
      }

      if (!this.categories[0].children) {
        return []
      }

      return this.categories[0].children;
    },
    handleCommand(command) {
      this.category = command;
      this.roster = this.getRoster(this.rosters, this.category);
      if (this.timer) {
        this.startHacking();
      }
      this.currentName = undefined;
    },
    deleteRow(row) {
      var name = row.name;
      var cat = row.category;
      var rosters = this.rosters;
      for (let idx in rosters) {
        var roster = rosters[idx]
        if (roster.name == name
          && roster.category == cat) {
          this.rosters.splice(idx, 1);

          localStorage.setItem("rosters", JSON.stringify(this.rosters));
          this.rosters = JSON.parse(localStorage.getItem("rosters"));
          break
        }
      }
    },
    dealId(nodes) {
      for (let i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        node.id = i + 1
      }
    },
    showAddNameView() {
      if (!this.searchCategory) {
        this.$message({
          type: 'info',
          showClose: true,
          duration: 3000,
          message: '请先在左侧选择要添加到哪个班级!'
        });
        return;
      }
      this.addStudentViewShow = true;
    },
    addNames() {
      if (!this.names) {
        this.addStudentViewShow = false;
        return;
      }
      var category = this.searchCategory;
      if (!category) {
        return;
      }
      var names = this.names.split("\n")
      for (let i = 0; i < names.length; i++) {
        var name = names[i].trim();
        if (name.length > 0) {
          this.rosters.push({
            "name": name,
            "category": category
          });
        }
      }

      localStorage.setItem("rosters", JSON.stringify(this.rosters));
      this.rosters = JSON.parse(localStorage.getItem("rosters"));
      this.addStudentViewShow = false;
      this.names = ""
    },
    addClass() {
      var that = this;
      this.$prompt('请输入班级', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        that.categories[0].children.push({
          "id": that.categories[0].children.length + 1,
          "label": value
        });

        localStorage.setItem("categories", JSON.stringify(that.categories));
        that.categories = JSON.parse(localStorage.getItem("categories"));
      }).catch(() => { });
    },
    removeRosters(rosters, category) {
      var rs = [];
      for (const idx in rosters) {
        var roster = rosters[idx]
        if (roster.category == category) {
          continue;
        }
        rs.push(roster);
      }
      return rs;
    },
    removeItem(items, item) {
      var its = []
      for (let idx = 0; idx < items.length; idx++) {
        const t = items[idx];
        if (t.id == item.id) {
          continue
        }
        its.push(t)
      }
      return its;
    },
    deleteClass(item) {
      var that = this;
      this.$confirm('是否删除(' + item.label + ')?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (that.searchCategory && item.label == that.searchCategory) {
          that.searchCategory = undefined;
        }
        var children = that.removeItem(that.categories[0].children, item);
        that.dealId(children);
        that.categories[0].children = children;
        localStorage.setItem("categories", JSON.stringify(that.categories));
        that.categories = JSON.parse(localStorage.getItem("categories"));

        var rosters = that.removeRosters(this.rosters, item.label);
        localStorage.setItem("rosters", JSON.stringify(rosters));
        this.rosters = JSON.parse(localStorage.getItem("rosters"));

        that.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => { });
    },
    chooseCategory(item, node, n) {
      if (item.id == 0) {
        this.searchCategory = undefined;
        return;
      }
      this.searchCategory = item.label;
    },
    initRoster() {
      this.roster = this.getRoster(this.rosters, this.category);
    },
    startHacking() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = undefined;
        this.starting = false;
        return;
      }

      var total = this.roster.length;
      if (total <= 0) {
        this.$message({
          type: 'info',
          showClose: true,
          duration: 2000,
          message: '(' + this.category + ')班级没有学生!'
        });
        return;
      }
      this.starting = true;
      this.timer = setInterval(this.startChoose, 100, this)
    },
    startChoose(that) {
      var total = that.roster.length;
      if (total <= 1) {
        return;
      }
      var idx = Math.floor(Math.random() * total);

      if (typeof that.lastIdx !== 'undefined'
        && that.lastIdx === idx) {
        idx = (idx + 1) % total;
      }

      that.lastIdx = idx
      that.currentName = that.roster[idx];
    },

    getDefaultCategories() {
      var dc = [{
        id: 0,
        label: '全部班级',
        children: [{
          id: 1,
          label: '默认班级',
        }]
      }]
      return JSON.stringify(dc);
    },
    initData() {
      var rosters = localStorage.getItem('rosters') || '[]';
      this.category = localStorage.getItem('category') || this.category;

      // 设置名单
      this.rosters = JSON.parse(rosters);
      this.roster = this.getRoster(this.rosters, this.category)

      // 设置类别
      var categories = localStorage.getItem('categories');
      if (!categories) {
        var defaultCategories = this.getDefaultCategories();
        categories = defaultCategories;
        localStorage.setItem('categories', categories);
      }
      this.categories = JSON.parse(categories);

    },
    getRoster(rosters, category) {
      if (!category) {
        return [];
      }
      var roster = [];
      for (let i = 0; i < rosters.length; i++) {
        const e = rosters[i];
        if (e.category == category) {
          roster.push(e.name)
        }
      }
      return roster;
    }
  },
  mounted: function () {
    var that = this;
    hotkeys('space', function (event, handler) {
      event.preventDefault()
      that.startHacking()
    });

    // 初始化rosters
    this.initData();

    // this.tableMaxHeight = this.$refs.table.height;
  }
}
</script>

<style>
#app {
  height: 100%;
}

#app #thumb-container {
  font-family: Helvetica, sans-serif;
  text-align: center;
}

.icon_tab {
  font-size: 30px;
  /* color: #555; */
  padding: 20px;
}

#app .el-tabs__nav-wrap::after {
  background-color: transparent;
}

#app .el-tabs__active-bar {
  display: none;
}

#category {
  margin-top: 50px;
  width: 300px;
  margin-left: calc(50% - 150px);
}

#name-container {
  margin-top: 50px;
  font-size: 100px;
  font-weight: 700;
  color: #222;
  font-family: "Lucida Calligraphy", cursive, serif, sans-serif;
}

#start-container {
  margin-top: 30px;
}

#setting-container {
  width: 700px;
  margin-left: calc(50% - 350px);
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: baseline;
}

#category-container {
  width: 200px;
  margin-right: 20px;
}

#category-container .el-tree-node {
  height: 38px;
}

#category-container .el-tree-node__content {
  height: 38px;
}

/* .el-tree-node.is-current .label {
  color: #409EFF;
} */

.custom-tree-node {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}


.custom-tree-node .el-icon-delete {
  margin-right: 10px;
  color: rgb(214 36 36);
  opacity: 0;
}

.el-tree-node__content:hover .custom-tree-node .el-icon-delete {
  opacity: 100;
}

.custom-tree-node .el-icon-plus {
  margin-right: 10px;
}

.el-dropdown-link {
  cursor: pointer;

}

.el-dropdown-link:hover {
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}

#roll-container {
  height: 98%;
}

.el-container.is-vertical {
  height: 100%;
}

/* .tree-node {
  font-size: 20px;
  padding-top: 17px;
  padding-bottom: 17px;
} */
</style>
